package student.aistar.day13;

import java.io.*;
import java.util.ArrayList;
import java.util.List;

public class ObjectStreamDemo2 {
    public static void main(String[] args) throws Exception {
        Book b1 = new Book(1,"1001","java",100.0d);
        Book b2 = new Book(2,"1002","java",100.0d);
        Book b3 = new Book(3,"1003","java",100.0d);
        List<Book> list = new ArrayList<>();
        list.add(b1);
        list.add(b2);
        list.add(b3);
        String path = "src/student/aistar/day13/books.txt";

        //写操作
        writeList(list, path);

        //读操作
//        List<Book> books = readList(path);
//        //1. 文件不存在 - java.io.FileNotFountException
//        //2. 文件存在, 文件为空 - java.io.EOFException
//        //3. 文件存在, 文件中也是有数据的, 但是这个数据的非法的流数据
//        //   - java.io.StreamCorruptedException: invalid stream header: E7BB8FE7
//        if(books != null && books.size() > 0){
//            for (Book book : books) {
//                System.out.println(book);
//            }
//        }
//        else System.out.println("数据错误");
    }

    //对象的反序列化操作
    private static List<Book> readList(String path) throws Exception {
        List<Book> list = null;
        try (ObjectInputStream in = new ObjectInputStream(new FileInputStream(path))){
            //从磁盘上的文件读入到内存中的集合中
            list = (List<Book>) in.readObject();
        }
        return list;
    }

    //对象的序列化过程
    private static void writeList(List<Book> list, String path) throws Exception {
        //只要运行一次, 就会清空文件 - 会直接覆盖文件中原来已经存在的数据
        try (ObjectOutputStream out = new ObjectOutputStream(new BufferedOutputStream(new FileOutputStream(path)))){

            //写出对象到磁盘的文件
            out.writeObject(list);
            System.out.println("保存成功");
        }

    }
}
